package com.zxjbyte.yiyi.framework.oss.rule;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.zxjbyte.yiyi.framework.common.constant.StringPool;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import lombok.RequiredArgsConstructor;

import java.util.Date;

/**
 * 存储桶生成规则
 * @Author zhangxingjia
 * @Date 2023/5/9 18:01
 * @Version: 1.0
 */
@RequiredArgsConstructor
public class OssRuleImpl implements OssRule {

    /**
     * 租户模式
     */
    private final Boolean tenantMode;

    @Override
    public String bucketName(String bucketName) {
        // 默认开启OSS租户模式，第一个分隔符（-）之前为租户数据
        String tenantId;
        if(tenantMode && (tenantId = AuthUtil.getTenantId()) != null){
            String subTenantId = StrUtil.subBefore(bucketName, StringPool.DASH, false);
            if(StrUtil.equals(bucketName, subTenantId)){
                return tenantId + StringPool.DASH + bucketName;
            } else if(StrUtil.equals(tenantId, subTenantId)){
                return bucketName;
            } else {
                return subTenantId + StringPool.DASH + StrUtil.subAfter(bucketName, StringPool.DASH, false);
            }
        } else {
            return bucketName;
        }
    }

    @Override
    public String fileName(String originalFilename) {
        return buildFileName(originalFilename, "file");
    }

    @Override
    public String fileNameByTenant(String originalFilename) {
        String tenantId = AuthUtil.getTenantId();
        // 未开启租户模式时使用常量：file，仅代表通用未开启租户，无特殊含义
        String keyword = "file";
        if(tenantMode && tenantId != null){
            keyword = tenantId;
        }
        return buildFileName(originalFilename, keyword);
    }

    private String buildFileName(String originalFilename, String keyword){
        return keyword + StringPool.SLASH + DateUtil.format(new Date(), "yyyyMMdd") + StringPool.SLASH + IdUtil.fastSimpleUUID() + StringPool.DOT + FileUtil.extName(originalFilename);
    }
}
